// <copyright file="UserController.cs" company="EnterpriseApi">
// Copyright (c) EnterpriseApi. All rights reserved.
// </copyright>

using EnterpriseApi.DTOs;
using EnterpriseApi.Models;
using EnterpriseApi.Services;
using Microsoft.AspNetCore.Mvc;

namespace EnterpriseApi.Controllers;

/// <summary>
/// 用户控制器，处理用户相关的HTTP请求
/// </summary>
[ApiController]                                                                                                                                                                                                                                         
[Route("api/[controller]")]
public class UserController : ControllerBase
{
    private readonly IUserService _userService;
    private readonly ILogger<UserController> _logger;

    /// <summary>
    /// 初始化UserController的新实例
    /// </summary>
    /// <param name="userService">用户服务</param>
    /// <param name="logger">日志记录器</param>
    public UserController(IUserService userService, ILogger<UserController> logger)
    {
        _userService = userService ?? throw new ArgumentNullException(nameof(userService));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    /// <summary>
    /// 获取所有用户
    /// </summary>
    /// <returns>用户列表</returns>
    [HttpGet]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public async Task<ActionResult<IEnumerable<UserDTO>>> GetAllUsers()
    {
        //获取所有用户
        Console.WriteLine("获取所有用户");

        try
        {
            Console.WriteLine("调用_userService.GetAllAsync()");
            var users = await _userService.GetAllAsync();
            Console.WriteLine($"获取到{users.Count()}个用户");
            
            var userDTOs = users.Select(user => new UserDTO
            {
                Id = user.Id,
                Username = user.Username,
                Email = user.Email,
                PhoneNumber = user.PhoneNumber,
                CreatedAt = user.CreatedAt,
                UpdatedAt = user.UpdatedAt,
                IsActive = user.IsActive,
                RoleName = user.Role?.Name ?? "Unknown"
            });
            return Ok(userDTOs);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"错误: {ex.Message}");
            Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");
            if (ex.InnerException != null)
            {
                Console.WriteLine($"内部错误: {ex.InnerException.Message}");
                Console.WriteLine($"内部堆栈跟踪: {ex.InnerException.StackTrace}");
            }
            _logger.LogError(ex, "获取所有用户时发生错误");
            return StatusCode(StatusCodes.Status500InternalServerError, "获取所有用户时发生错误: " + ex.Message);
        }
    }

    /// <summary>
    /// 根据ID获取用户
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <returns>用户详情</returns>
    [HttpGet("{id}")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<UserDTO>> GetUserById(int id)
    {
        try
        {
            var user = await _userService.GetByIdAsync(id);
            if (user == null)
            {
                return NotFound();
            }

            var userDTO = new UserDTO
            {
                Id = user.Id,
                Username = user.Username,
                Email = user.Email,
                PhoneNumber = user.PhoneNumber,
                CreatedAt = user.CreatedAt,
                UpdatedAt = user.UpdatedAt,
                IsActive = user.IsActive,
                RoleName = user.Role?.Name ?? "Unknown"
            };
            return Ok(userDTO);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取用户详情时发生错误");
            return StatusCode(StatusCodes.Status500InternalServerError, "获取用户详情时发生错误");
        }
    }

    /// <summary>
    /// 创建新用户
    /// </summary>
    /// <param name="user">用户信息</param>
    /// <returns>创建的用户</returns>
    [HttpPost]
    [ProducesResponseType(StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<ActionResult<UserDTO>> CreateUser([FromBody] User user)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        try
        {
            // 这里简化处理，实际应用中应该使用专门的注册DTO并包含密码参数
            var password = "DefaultPassword123!"; // 实际应用中不应硬编码密码
            var createdUser = await _userService.RegisterUserAsync(user, password);

            var userDTO = new UserDTO
            {
                Id = createdUser.Id,
                Username = createdUser.Username,
                Email = createdUser.Email,
                PhoneNumber = createdUser.PhoneNumber,
                CreatedAt = createdUser.CreatedAt,
                UpdatedAt = createdUser.UpdatedAt,
                IsActive = createdUser.IsActive,
                RoleName = createdUser.Role?.Name ?? "Unknown"
            };
            return CreatedAtAction(nameof(GetUserById), new { id = createdUser.Id }, userDTO);
        }
        catch (ArgumentException ex)
        {
            _logger.LogError(ex, "创建用户时发生错误");
            return BadRequest(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建用户时发生错误");
            return StatusCode(StatusCodes.Status500InternalServerError, "创建用户时发生错误");
        }
    }

    /// <summary>
    /// 更新用户信息
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <param name="user">更新的用户信息</param>
    /// <returns>更新后的用户</returns>
    [HttpPut("{id}")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<UserDTO>> UpdateUser(int id, [FromBody] User user)
    {
        if (id != user.Id)
        {
            return BadRequest("用户ID不匹配");
        }

        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        try
        {
            var existingUser = await _userService.GetByIdAsync(id);
            if (existingUser == null)
            {
                return NotFound();
            }

            user.UpdatedAt = DateTime.UtcNow;
            var updatedUser = await _userService.UpdateAsync(user);

            var userDTO = new UserDTO
            {
                Id = updatedUser.Id,
                Username = updatedUser.Username,
                Email = updatedUser.Email,
                PhoneNumber = updatedUser.PhoneNumber,
                CreatedAt = updatedUser.CreatedAt,
                UpdatedAt = updatedUser.UpdatedAt,
                IsActive = updatedUser.IsActive,
                RoleName = updatedUser.Role?.Name ?? "Unknown"
            };
            return Ok(userDTO);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新用户信息时发生错误");
            return StatusCode(StatusCodes.Status500InternalServerError, "更新用户信息时发生错误");
        }
    }

    /// <summary>
    /// 删除用户
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <returns>删除结果</returns>
    [HttpDelete("{id}")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> DeleteUser(int id)
    {
        try
        {
            var user = await _userService.GetByIdAsync(id);
            if (user == null)
            {
                return NotFound();
            }

            await _userService.DeleteAsync(id);
            return NoContent();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除用户时发生错误");
            return StatusCode(StatusCodes.Status500InternalServerError, "删除用户时发生错误");
        }
    }

    /// <summary>
    /// 获取活跃用户列表
    /// </summary>
    /// <returns>活跃用户列表</returns>
    [HttpGet("active")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public async Task<ActionResult<IEnumerable<UserDTO>>> GetActiveUsers()
    {
        try
        {
            var activeUsers = await _userService.GetActiveUsersAsync();
            var userDTOs = activeUsers.Select(user => new UserDTO
            {
                Id = user.Id,
                Username = user.Username,
                Email = user.Email,
                PhoneNumber = user.PhoneNumber,
                CreatedAt = user.CreatedAt,
                UpdatedAt = user.UpdatedAt,
                IsActive = user.IsActive,
                RoleName = user.Role?.Name ?? "Unknown"
            });
            return Ok(userDTOs);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取活跃用户列表时发生错误");
            return StatusCode(StatusCodes.Status500InternalServerError, "获取活跃用户列表时发生错误");
        }
    }
}